package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.common.exception.NoStockException;
import com.atguigu.gulimall.common.to.OrderTo;
import com.atguigu.gulimall.common.to.SkuHashStockVo;
import com.atguigu.gulimall.common.to.mq.SecKillOrderTo;
import com.atguigu.gulimall.common.utils.R;
import com.atguigu.gulimall.common.vo.MemberVo;
import com.atguigu.gulimall.order.config.MyMqConfig;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.enmu.OrderStatusEnum;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.inteceptor.OrderInteceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    public static final ThreadLocal<OrderSubmitVo> confirmThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor poolExecutor;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confrimPay() {
        MemberVo memberVo = OrderInteceptor.threadLocal.get();

        OrderConfirmVo confirmVo = new OrderConfirmVo();

        // 得到线程的requestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 使用异步编排优化
        CompletableFuture<Void> memberFeign = CompletableFuture.runAsync(() -> {

            // 手动加入requestAttributes
            RequestContextHolder.setRequestAttributes(requestAttributes);

            // 远程调用会员服务接口得到收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberVo.getId());
            confirmVo.setAddress(address);
        }, poolExecutor);


        CompletableFuture<Void> cartFeign = CompletableFuture.runAsync(() -> {
            // 手动加入requestAttributes
            RequestContextHolder.setRequestAttributes(requestAttributes);

            // 远程调用购物车接口
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItem();
            confirmVo.setItems(items);

            // feign在远程调用之前要构造请求，调用很多的拦截器
        }, poolExecutor).thenRunAsync(() -> {
                    // 1. 如果我们在Item类中加入hasStock属性，就需要遍历得到数据
                    // 2. 我们可以在OrderItemVo中加入一个Map，保存skuId,hasStock，这样只需要远程调用一次
                    List<OrderItemVo> items = confirmVo.getItems();
                    List<Long> skuIdList = items.stream().map(item -> {
                        return item.getSkuId();
                    }).collect(Collectors.toList());

                    List<SkuHashStockVo> skuHashStockVos = wareFeignService.hasStock(skuIdList);

                    // 将其保存到Map中
                    if (skuHashStockVos != null) {
                        Map<Long, Boolean> map = skuHashStockVos.stream().collect(Collectors.toMap(SkuHashStockVo::getSkuId, SkuHashStockVo::getHasStock));
                        confirmVo.setStocks(map);
                    }
                }
                , poolExecutor);

        // 得到会员积分
        confirmVo.setIntegration(memberVo.getIntegration());

        //TODO 令牌防重复提交
        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId(), uuid);
        confirmVo.setOrderToken(uuid);


        // 等待所有异步任务执行完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(memberFeign, cartFeign);
        try {
            allOf.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        return confirmVo;
    }

    //  下单，去创建订单，验令牌，验价格，锁库存
    @Override
//    @GlobalTransactional
    @Transactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();

        MemberVo memberVo = OrderInteceptor.threadLocal.get();

        // 验证令牌
        // 原子（查询锁，对比锁，删除锁）
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        // key  value
        Long code = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()), vo.getOrderToken());
        redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
        // 当code为0表示不存在
        if (code == 0L) {
            responseVo.setCode(1);
            return responseVo;
        } else {
            // 执行后面操作
            OrderCreateTo order = createOrder();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 保存订单
                saveOrder(order);
                // 库存锁定（错误回滚）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemEntity> orderItems = order.getOrderItems();
                List<OrderItemVo> locks = orderItems.stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                R r = wareFeignService.orderLockStock(lockVo);
                Integer result = (Integer) r.get("code");
                if (result == 0) {
                    // 成功
//                    int i = 10 / 0;
                    responseVo.setOrder(order.getOrder());
                    responseVo.setCode(0);
                    // 发送消息到 mq
                    rabbitTemplate.convertAndSend(MyMqConfig.ORDER_EVENT_EXCHAGE, MyMqConfig.DELAY_QUEUE_ROUTINGKEY, order.getOrder());
                    return responseVo;
                } else {
                    throw new NoStockException(1L);
                }
            } else {
                responseVo.setCode(3);
                return responseVo;
            }
        }
    }

    @Override
    public OrderEntity hasOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }


    // 订单关闭方法
    @Override
    public void orderClose(OrderEntity orderEntity) {
        Long id = orderEntity.getId();
        OrderEntity byId = this.getById(id);
        // 如果该商品是已取消状态
        if (byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            OrderEntity order = new OrderEntity();
            order.setId(id);
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(order);
            // 避免订单发送给mq时卡顿，导致库存系统发送给mq比订单系统快
            // 就会导致库存系统不会解锁订单（判断为4（已关闭才回滚库存））
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(byId,orderTo);
            rabbitTemplate.convertAndSend(MyMqConfig.ORDER_EVENT_EXCHAGE,MyMqConfig.ORDER_RELEASE_OTHER,orderTo);
        }
    }


    private void saveOrder(OrderCreateTo order) {
        OrderEntity entity = order.getOrder();
        entity.setModifyTime(new Date());
        this.save(entity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        if (orderItems != null && orderItems.size() > 0) {
            for (OrderItemEntity orderItem : orderItems) {
                orderItemService.save(orderItem);
            }
        }
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        // 生成订单号
        String orderSn = IdWorker.getTimeId();
        // 创建订单
        OrderEntity orderEntity = buildOrderEntity(orderSn);

        // 获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        // 计算价格相关
        computePrice(orderEntity, itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);


        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal gift = new BigDecimal("0");
        BigDecimal growth = new BigDecimal("0");
        for (OrderItemEntity entity : itemEntities) {
            BigDecimal realAmount = entity.getRealAmount();
            coupon.add(entity.getRealAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(realAmount);
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }

        // 订单价格相关
        orderEntity.setTotalAmount(total);
        // 应付
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        // 设置积分信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);
    }

    private OrderEntity buildOrderEntity(String orderSn) {

        MemberVo memberVo = OrderInteceptor.threadLocal.get();

        // 创建订单号
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberVo.getId());

        OrderSubmitVo submitVo = confirmThreadLocal.get();
        // 获取收货地址信息
        R r = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fare = (FareVo) r.getData("fare", new TypeReference<FareVo>() {
        });

        entity.setFreightAmount(fare.getFare());
        entity.setReceiverDetailAddress(fare.getMemberAddressVo().getDetailAddress());
        entity.setReceiverName(fare.getMemberAddressVo().getName());
        entity.setReceiverPhone(fare.getMemberAddressVo().getPhone());
        entity.setReceiverPostCode(fare.getMemberAddressVo().getPostCode());
        entity.setReceiverProvince(fare.getMemberAddressVo().getProvince());
        entity.setReceiverRegion(fare.getMemberAddressVo().getRegion());

        // 设置订单的相关状态
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    // 构建订单项
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        if (currentUserCartItem != null && currentUserCartItem.size() > 0) {
            List<OrderItemEntity> collect = currentUserCartItem.stream().map(item -> {
                OrderItemEntity itemEntity = buildOrderItem(item);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity itemEntity = new OrderItemEntity();

        Long skuId = item.getSkuId();
        R r = productFeignService.getSpuInfo(skuId);
        SpuInfoVo spuInfo = (SpuInfoVo) r.getData("spuInfo", new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(spuInfo.getId());
        itemEntity.setSpuBrand(spuInfo.getBrandId().toString());
        itemEntity.setSpuName(spuInfo.getSpuName());
        itemEntity.setCategoryId(spuInfo.getCatalogId());


        itemEntity.setSkuId(item.getSkuId());
        itemEntity.setSkuName(item.getTitle());
        itemEntity.setSkuPic(item.getImage());
        String s = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ",");
        itemEntity.setSkuAttrsVals(s);
        itemEntity.setSkuQuantity(item.getCount());

        //积分信息
        itemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());

        // 价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));

        BigDecimal orign = item.getPrice().multiply(new BigDecimal(item.getCount()));
        itemEntity.setRealAmount(orign);


        return itemEntity;
    }


    // 生成秒杀订单方法
    @Transactional
    @Override
    public void createKillOrder(SecKillOrderTo orderTo) {
        // 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        BigDecimal multiply = orderTo.getSeckillPrice().multiply(new BigDecimal(orderTo.getNum() + ""));
        orderEntity.setPayAmount(multiply);
        baseMapper.insert(orderEntity);

        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(orderTo.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(orderTo.getNum());
        // TODO：获取当前sku的详细信息进行设置
        orderItemService.save(itemEntity);
    }

}